package com.ruipeng.shengyapo.locksocket;

import java.text.DecimalFormat;
import java.util.Map;
import java.util.TreeMap;

import com.ruipeng.shengyapo.utils.HttpUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import org.apache.log4j.Logger;

public class LockServerHandler extends ChannelHandlerAdapter {
	
	private static String serverUrl = "http://59.110.235.98:80/sypappservice";

	private static Logger log = Logger.getLogger("lock");
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		NettyChannelMap.remove((SocketChannel) ctx.channel());
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];// 获得缓冲区可读的字节数
		buf.readBytes(req);
		String body = new String(req, "US-ASCII");
		if (!body.startsWith("*CMDR")) {
			return;
		}
		body = body.substring(1, body.length() - 2); // 去掉首位标识符

        //System.out.println("接受到锁的数据包 : " + body);
        log.info("接受到锁的数据包 : " + body);

        Map<String, String> orderMap = analyseOrder(body);
		System.out.println("orderMap : " + orderMap);

		if (orderMap != null) {
			String imei = orderMap.get("DeviceIMEI");
			if (imei.length() == 15) { // 缓存Channel
				NettyChannelMap.add(orderMap.get("DeviceIMEI"), (SocketChannel) ctx.channel());
			}

			String orderType = orderMap.get("OrderType");
			if ("Q0".equals(orderType)) { // 签到
                log.info("签到包");
			} else if ("H0".equals(orderType)) { // 心跳
                log.info("心跳包");
			} else if ("I0".equals(orderType)) { // iccid
                log.info("获取SIM卡信息包");

                String iccid = orderMap.get("iccid");
				String result = HttpUtils.sendPost("http://120.24.228.199:8088/BikeProduce/test?imei=" + imei + "&iccid=" + iccid, "");
				//System.out.println("获取iccid " + result);
                log.info("获取iccid " + result);

			} else if ("S0".equals(orderType)) { // 关机
				//System.out.println("关机包");
                log.info("关机包 ");

			} else if ("D0".equals(orderType)) { // 定位
				//System.out.println("定位包");
                log.info("定位包 ");
				System.out.println("orderMap: " + orderMap);
				
				if ("1".equals(orderMap.get("hasLocation"))) {
					//更新自行车最新位置
					String location = orderMap.get("longitude") + "," + orderMap.get("latitude");

					System.out.println("location="+location);

					HttpUtils.sendPost(serverUrl + "/lock/updateBikeLocation?imei=" + imei + "&location=" + location, "");
					
					// 查询最新订单是否推送终点
					String set_endPath = HttpUtils.sendPost(serverUrl + "/lock/getRecentOrderIsSetEndPath?imei=" + imei, "");
					System.out.println("set_endPath: " + set_endPath);
					
					if ("0".equals(set_endPath)) {
						// 设置已发送订单终点位置
						HttpUtils.sendPost(serverUrl + "/lock/setEndPath?imei=" + imei + "&location=" + location, "");
					}
				}
			} else if ("L1".equals(orderType)) { // 锁头上报上锁
				//System.out.println("自行车" + imei + "骑行已结束！");
                log.info("自行车" + imei + "骑行已结束！");
				// 发送获取定位指令
				LockManager.getLocationCmd(imei);
				System.out.println("send Location command...");

				HttpUtils.sendPost(serverUrl + "/lock/closeLock?imei=" + imei, "");
			}else if("L0".equals(orderType)){
			    //开锁成功
                HttpUtils.sendPost(serverUrl + "/lock/updateLockState?lockState=1&imei=" + imei, "");
            }
		}

		// ByteBuf resp = Unpooled.copiedBuffer(getOpenLockCmd());
		// ctx.write(resp);// 性能考虑，仅将待发送的消息发送到缓冲数组中，再通过调用flush方法，写入channel中
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();// 将消息发送队列中的消息写入到SocketChannel中发送给对方。
	}

	private Map<String, String> analyseOrder(String order) {
		// *CMDR,XX,863158022988725,161201150000,Q0,412#
		String[] orders = order.split(",");
		if (orders.length < 5 && orders.length > 2 && orders[2].length() != 15) { // 至少5个参数，imei固定15位
			return null;
		}
		Map<String, String> orderMap = new TreeMap<String, String>();
		orderMap.put("DeviceIMEI", orders[2]);
		orderMap.put("OrderType", orders[4]);

		switch (orders[4]) {
		case "D0": // 定位
		{
			/**
			 * [6]:UTC时间
			 * [7]定位状态，A=有效定位，V=无效定位 
			 * [8]纬度 ddmm.mmmm(度分)格式(前面的 0 也将被传输)
			 * [9]纬度半球 N(北半球)或 S(南半球
			 * [10]经度 dddmm.mmmm(度分)格式(前面的 0 也将被传输)
			 * [11]经度半球 E(东经)或 W(西经)
			 */
			if ("A".equals(orders[7])) { // 有效定位
				orderMap.put("hasLocation", "1");
				String latitude = orders[8];
				String latDu = latitude.substring(0, 2);
				
				DecimalFormat df = new DecimalFormat(".######"); // 小数点后6位
				
				double latDouble = Double.parseDouble(latitude.substring(2)) / 60;
				String latDec = df.format(latDouble);
				
				String longitude = orders[10];
				String lonDu = longitude.substring(0, 3);
				
				double lonDouble = Double.parseDouble(longitude.substring(3)) / 60;
				String lonDec = df.format(lonDouble);
				
				orderMap.put("latitude", latDu + latDec);
				orderMap.put("longitude", lonDu + lonDec);
			}
		}
		case "I0": // 获取SIMCard信息
		{
			// 接受到锁的数据包 : CMDR,XX,000000000000000,000000000000,I0,898602B8191750149366
			System.out.println("iccid:" + orders[5]);
			orderMap.put("iccid", orders[5]);
		}
		}

		return orderMap;
	}
}
